package br.com.assessoriaesportiva.dao;

import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;
import javax.persistence.Query;

import br.com.assessoriaesportiva.jpautil.Transacional;
@Transacional
public abstract class CrudDaoImp<T> implements CrudDAO<T> {

	@SuppressWarnings("unchecked")
	public List<T> buscarPorNQ(String namedQuery, Map<String, Object> params) {
		Query query = getEm().createNamedQuery(namedQuery);

		if (params != null && params.size() > 0) {
			Set<String> keySet = params.keySet();
			for (String chave : keySet) {
				query.setParameter(chave, params.get(chave));
			}
		}
		try {
			return (List<T>) query.getResultList();
		} catch (NoResultException erro) {
			return null;
		}
	}

	@Override
	public void atualizar(T t) {
		getEm().merge(t);
	}

	@Override
	public void excluir(T t) {
		t = getEm().merge(t);
		getEm().remove(t);
	}

	public abstract EntityManager getEm();

}
